package com.ruoyi.wvp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.DeletedEnum;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.wvp.domain.Surveillance;
import com.ruoyi.wvp.domain.SurveillanceEvent;
import com.ruoyi.wvp.sdk.monitor.IMonitorSdkService;
import com.ruoyi.wvp.sdk.monitor.entity.params.LiveHistoryParams;
import com.ruoyi.wvp.sdk.monitor.entity.response.LiveHistoryInfo;
import com.ruoyi.wvp.sdk.monitor.entity.response.LiveInfo;
import com.ruoyi.wvp.service.ISurveillanceEventService;
import com.ruoyi.wvp.service.ISurveillanceService;
import com.ruoyi.wvp.task.SyncDeviceStatusTask;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * AI摄像头Controller
 *
 * @author ruoyi
 * @date 2024-07-20
 */
@RestController
@RequestMapping("/wvp/surveillance")
@Tag(name = "【AI摄像头】管理")
public class SurveillanceController extends BaseController {
    @Autowired
    private ISurveillanceService surveillanceService;

    @Autowired
    private IMonitorSdkService iMonitorSdkService;

    @Autowired
    private ISurveillanceEventService surveillanceEventService;

    /**
     * 查询AI摄像头列表
     */
    @Operation(summary = "查询AI摄像头列表")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:list')")
    @GetMapping("/list")
    public TableDataInfo list(Surveillance surveillance) {
        Page<Surveillance> page = getPage();
        Page<Surveillance> surveillancePage = surveillanceService.pageList(page, surveillance);
        return getTableDataInfo(page);
    }

    @Operation(summary = "查询AI摄像头列表")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:list')")
    @PostMapping("/listAll")
    public AjaxResult listAll(@RequestBody Surveillance surveillance) {
        List<Surveillance> data = surveillanceService.listAll(surveillance);
        return  AjaxResult.success(data);
    }


    /**
     * 导出AI摄像头列表
     */
    @Operation(summary = "导出AI摄像头列表")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:export')")
    @Log(title = "AI摄像头", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportAll(HttpServletResponse response, Surveillance surveillance) {
        List<Surveillance> list = surveillanceService.listAll(surveillance);
        list.forEach(item -> {
            if (Objects.nonNull(item.getDeviceStatus())) {
                item.setDeviceStatusStr(DictUtils.getDictLabel(CacheConstants.WVP_DEVICE_STATUS, item.getDeviceStatus().toString()));
            }
        });
        ExcelUtil<Surveillance> util = new ExcelUtil<Surveillance>(Surveillance.class);
        util.exportExcel(response, list, "设备数据", "AI摄像头");
    }

    /**
     * 获取AI摄像头详细信息
     */
    @Operation(summary = "获取AI摄像头详细信息")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(surveillanceService.getById(id));
    }

    /**
     * 新增AI摄像头
     */
    @Operation(summary = "新增AI摄像头")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:add')")
    @Log(title = "AI摄像头", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Surveillance surveillance) {
        surveillance.setDeleted(DeletedEnum.NOMAL.getValue());
        surveillance.setCreateBy(getUsername());
        surveillance.setCreateTime(new Date());
        return toAjax(surveillanceService.save(surveillance));
    }

    /**
     * 修改AI摄像头
     */
    @Operation(summary = "修改AI摄像头")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:edit')")
    @Log(title = "AI摄像头", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Surveillance surveillance) {
        surveillance.setUpdateBy(getUsername());
        surveillance.setUpdateTime(new Date());
        return toAjax(surveillanceService.updateById(surveillance));
    }

    /**
     * 删除AI摄像头
     */
    @Operation(summary = "删除AI摄像头")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:remove')")
    @Log(title = "AI摄像头", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable(name = "ids") String[] ids) {
        QueryWrapper<Surveillance> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", List.of(ids));
        Surveillance surveillance = new Surveillance();
        surveillance.setUpdateTime(new Date());
        surveillance.setUpdateBy(getLoginUser().getUser().getUserName());
        surveillance.setDeleted(DeletedEnum.DELETED.getValue());
        return toAjax(surveillanceService.update(surveillance, queryWrapper));
    }


    @Operation(summary = "获取设备直播地址")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:live')")
    @PostMapping("/live/{id}")
    public AjaxResult getLiveInfo(@PathVariable Long id) {
        Surveillance surveillance = surveillanceService.getById(id);
        if (Objects.isNull(surveillance)) {
            return AjaxResult.error("未找到该设备");
        }
        LiveInfo liveInfo = iMonitorSdkService.getLiveInfo(surveillance);
        return AjaxResult.success(liveInfo);
    }

    @Operation(summary = "获取设备直播地址")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:historyLiv')")
    @PostMapping("/historyLiv/{id}")
    public AjaxResult getHistoryLive(@PathVariable Long id, @RequestBody LiveHistoryParams params) {
        Surveillance surveillance = surveillanceService.getById(id);
        if (Objects.isNull(surveillance)) {
            return AjaxResult.error("未找到该设备");
        }
        params.setType(2);
        params.setProtocol(4);
        params.setDeviceSerial(surveillance.getDeviceNumber()+"#1");
//        params.setExpireTime(0);
        LiveHistoryInfo liveInfo = iMonitorSdkService.getLiveHistoryInfo(params);
        return AjaxResult.success(liveInfo);
    }

    @Operation(summary = "事件列表")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:eventList')")
    @PostMapping("/eventList/{id}")
    public TableDataInfo getEventList(SurveillanceEvent surveillanceEvent) {
        Page<SurveillanceEvent> page = getPage();
        surveillanceEventService.pageList(page, surveillanceEvent);
        return getTableDataInfo(page);
    }


    @Operation(summary = "导入AI摄像头列表")
    @Log(title = "AI摄像头管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<Surveillance> util = new ExcelUtil<Surveillance>(Surveillance.class);
        List<Surveillance> list = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = surveillanceService.importSurveillance(list, updateSupport, operName);
        return success(message);
    }

    @Operation(summary = "获取导入AI摄像头模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Surveillance> util = new ExcelUtil<Surveillance>(Surveillance.class);
        util.importTemplateExcel(response, "AI摄像头数据");
    }


    @PostMapping("/syncDeviceStatus")
    @PreAuthorize("@ss.hasPermi('wvp:surveillance:syncDeviceStatus')")
    public AjaxResult syncDeviceStatus() throws ExecutionException, InterruptedException {
        SyncDeviceStatusTask syncDeviceStatusTask = SpringUtils.getBean(SyncDeviceStatusTask.class);
        CompletableFuture<Boolean> uCompletableFuture = CompletableFuture.supplyAsync(() -> {
             syncDeviceStatusTask.updateSurveillanceStatus();
             return true;
        }, SyncDeviceStatusTask.executorService);
        Boolean o = uCompletableFuture.get();
        return success(o);
    }


}
